const base_url = 'http://123.57.179.172:6191/'

export const post = (url, params, ext) => {
  return new Promise((resolve, reject) => {
    let api = base_url + url
    let headers = {
      'content-type': 'application/json',
    }
    if (ext && ext.headers) {
      Object.assign(headers, ext.headers)
    }
    let data = undefined
    if (ext && ext.encrypt === false) {
      data = params || {};
    } else {
      data = {
        endec: 'on',
        params: wx.$crypto.encrypt(JSON.stringify(params || {})),
        token: 'v120',
      }
    }
    let ticket = wx.$storage.get('ticket')
    if (ticket) {
      headers['Authorization'] = 'Bearer ' + ticket;
    }
    console.log('$REQ', api, params || {});
    let result = undefined;
    if (ext && ext.dialog) {
      wx.$model.loading();
    }
    wx.request({
      method: 'POST',
      dataType: 'json',
      url: api,
      data: data,
      header: headers,
      success: (res) => {
        let r = res.data
        if (r.token === 'v120' && typeof r.result === 'string') {
          result = JSON.parse(wx.$crypto.decrypt(r.result))
        } else {
          result = r;
        }
        resolve(result)
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        if (ext && ext.dialog) {
          setTimeout(() => {
            wx.$model.closeLoading();
          }, 500)
        }
      }
    })
  })
}

export const get = (url, params, ext) => {

}

